using System;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace BrettM.Web.Restful
{
    /// <summary>
    /// This controller factory is registered in when the RegisterControllerFactor bootstrapper is called and
    /// is responsoble for creating instances of the requested controller.  The factory will attempt to create
    /// an instance of the controller using the dependency incjection container.
    /// </summary>
    public class RestControllerFactory
        : DefaultControllerFactory
    {
        private readonly IUnityContainer _container;

        /// <summary>
        /// The constructor requiring an instance of the container
        /// </summary>
        /// <param name="container"></param>
        public RestControllerFactory(IUnityContainer container)
        {
            if (container == null) throw new ArgumentNullException("container");

            _container = container;
        }

        /// <summary>
        /// Creates an instance of the controller  based on the full name of the controller, if this fails the 
        /// base factory will be used.
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="controllerType"></param>
        /// <returns></returns>
        /// <remarks>
        /// The DebuggerNonUserCode stops the debuger breaking in this bit of code for non RESTful controllers
        /// </remarks>
        [DebuggerNonUserCode]
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            IController controller;

            try
            {
                controller = _container.Resolve<IRestController>(controllerType.FullName) as IController;
            }
            catch
            {
                controller = base.GetControllerInstance(requestContext, controllerType);

            }
            return controller;
        }
    }
}
